<?php
/**
 * Created by IntelliJ IDEA.
 * User: WuDun 123677924@qq.com
 * Date: 2019/7/1
 * Time: 17:55
 */

namespace api\api\controller;

use cmf\controller\RestBaseController;
use think\facade\Env;
use think\Db;
use api\api\service\IndexService;

class AlipayController extends RestBaseController
{

    /*
         * 积分商城支付宝支付加密字符串获取
         * app支付生成预支付码方法封装  dunge
         */
    public function getOrderstring($body_content, $order_sn)
    {
        //判断是否是登录的用户调用的本接口
       $this->getUserId();
        $total_fee = Db::name('order')->where(array('order_number' => $order_sn))->value('real_amount');
        $param = ['subject' => $body_content, 'out_trade_no' => $order_sn, 'total_amount' => 0.01];
        $result = hook_one("alipay_get_order_id", $param);
        $this->success('支付秘需参数创建成功', $result);
    }


    /**
     * 写日志，方便测试（看网站需求，也可以改成把记录存入数据库）
     * 注意：服务器需要开通fopen配置
     * @param $word 要写入日志里的文本内容 默认值：空值
     */
    public function logResult($word = '')
    {
        if (!is_dir("paylog/" . date('YmdH'))) {
            mkdir("paylog/" . date('YmdH'), "0777", true);
        } else {
        }
        return file_put_contents("paylog/" . date('YmdH') . "/log.txt", "执行时间：" . date("Y-m-d H:i:s") . $word . "-----华丽的分割线------", FILE_APPEND);

    }
	/*
	     * 回调
	     */
	    public function notify_url()
	    {
	        //引入入口，加载配置
	        include Env::get('root_path') . "public/plugins/ali_pay/include.php";
	        $config = Db::name('plugin')->where('name', 'AliPay')->value('config');
	        if (!empty($config) && $config != "null") {
	            $config = json_decode($config, true);
	            try {
	                // 实例支付对象
	                $pay = \We::AliPayApp($config);
	                // $pay = new \AliPay\App($config);
	                $data = $pay->notify();
	                $this->logResult("支付数据post==" . json_encode($data));
	                if (in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
	                    // @todo 更新订单状态，支付完成
	                    $out_trade_no = $data['out_trade_no'];
	                    // $total_fee2 = $data['total_fee'];
	                        $wheretrade_no['order_number'] = $out_trade_no;
	                        $result = Db::name('order')->where($wheretrade_no)->where(array('pay_status' => 0))->find();
	                        if (!empty($result)) {
	                            $userid = $result['user_id'];
	                            $real_amount = $result['real_amount'];
	                            //开启事务
	                            Db::startTrans();
	                            //支付完成逻辑
	                            $data_pay['pay_status'] = 1;
	                            $data_pay['pay_method'] = 1;
	                            //更新订单表支付数据和状态
	                            $ret_pay = Db::name('order')->where($wheretrade_no)->update($data_pay);
	
	                            $remark_msg = '支付订单'.$out_trade_no.$real_amount.'元';
	                            $balanceLog = userbalanceLog($userid, 1, 2, $real_amount, '', $remark_msg, $result['order_id'], '');
                                //如果订单司机以送达  则代表完成 zjf
                                if($result['status'] == 4 ){
                                    Db::name('order')->where($wheretrade_no)->update(array('status'=>5,'finish_time'=>time()));
                                    fenrun($result['order_id']);

                                }
								if($result['status'] > 1 ){

									//消息推送
									$indexService = new IndexService();
									$refund_ = $indexService->jpush_send_user(1,'支付完成,订单(' . $out_trade_no . ')已支付',$userid);
								}
	                            if (!$ret_pay || !$balanceLog) {
	                                Db::rollback();
	                                //记录异常到log.txt文件
	                                $this->logResult('订单' . $out_trade_no . '支付宝支付成功,但本系统状态未更新，请联系客服处理');
	                            }
								//派单
								order_auto_designate($result['order_id']);
	                            Db::commit();
	                            //处理完成之后，告诉支付宝成功结果！
	                            echo 'success';
	                            exit();
	                        } else {
	                            $this->logResult('error');
	                            echo 'error';
	                        }
	                } else {
	                    echo 'error';
	//                file_put_contents('notify.txt', "收到异步通知\r\n", FILE_APPEND);
	                }
	            } catch (\Exception $e) {
	                // 异常处理
	                echo $e->getMessage();
	            }
	
	        } else {
	            echo 'error';
	        }
	
	    }
		
		/*
		 * 积分商城支付宝支付退款
		 * app支付生成退款方法封装  dunge
		 */
		public function setOrderrefund($order_sn)
		{
		    //判断是否是登录的用户调用的本接口
		    $userid = $this->getUserId();
			if (!$order_sn){
				$this->error("参数为空");
			}
			
			$indexService = new IndexService();
			$order_obj_ = $indexService->get_order_obj($order_sn,$userid,'user_id');
			
			$result = '';
			$status     = $order_obj_['status'];
			$order_id   = $order_obj_['order_id'];
			$pay_status = $order_obj_['pay_status'];
			$total_fee = $order_obj_['real_amount'];
			$remark_msg = '您取消了订单(' . $order_sn . '),已退款'.$total_fee.'元到支付宝';
			
			if (!$order_obj_){
				$this->error("订单号有误");
				}
			if ($status > 2){
				$this->error("订单状态有误");
				}
//				Db::startTrans(); //开启事务
			// try {
				
				$data_pay['pay_status'] = 2;
				$data_pay['status']     = 6;
				$update_ = $indexService->update_order_obj_array($order_id,$data_pay);
				// $update_ = $indexService->update_order_obj($order_id,'status',6);//更新订单状态
				//取消日志
				$msg_ret = create_user_message(1,$userid, '取消订单', $remark_msg, $remark_msg);
				if($pay_status == 1){
					$param = ['out_trade_no' => $order_sn, 'total_amount' => 0.01];
					$result = hook_one("alipay_order_refund", $param);
					if($result['code'] != '10000'){
//						Db::rollback();
						$this->error("订单取消失败");
					}
				}
				if($status > 0){//是否已接单
					$up_cancle_ = $indexService->up_user_param($userid,'cancle_num',1);
					//司机消息推送
					$refund_ = $indexService->jpush_send_driver(2,'订单取消，单号(' . $order_sn . ')用户已取消',$order_obj_['driver_id']);
				}
				//消息推送
				$refund_ = $indexService->jpush_send_user(1,'您的订单(' . $order_sn . ')取消成功',$userid);
				if(!$update_ ){
//					Db::rollback();
					$this->error("订单取消失败");
				}
				// 提交事务
//				Db::commit();
				$this->success('支付宝退款成功', $result);
			// } catch (\Exception $e) {
			// 	// 回滚事务
			// 	Db::rollback();
			// 	$this->error("订单取消失败");
			// }
			
			
			
		 //    $total_fee = Db::name('order')->where(array('order_number' => $order_sn))->value('real_amount');
		 //    $param = ['out_trade_no' => $order_sn, 'total_amount' => 0.01];
		 //    $result = hook_one("alipay_order_refund", $param);
			// if($result.code == '10000'){
			// 	
			// }
		 //    $this->success('支付宝退款成功', $result);
		}
}